完成資料庫的設置後,接著我們就能為第一筆資料(Bootcamp)訂定Schema!
首先,建立一個models資料夾,並在裡面創建Bootcamp.js file
const mongoose = require('mongoose');
const BootcampSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name'],
unique: true,
trim: true,
maxlength: [50, 'Name cannot be more than 50 characters']
},
slug: String,
description: {
type: String,
required: [true, 'Please add a description'],
maxlength: [500, 'Description cannot be more than 500 characters']
},
careers: {
type: [String],
required: true,
enum: [
'Web Development',
'Mobile Development',
'UI/UX',
'Data Science',
'Business',
'Other'
]
},
address: {
type: String,
required: [true, 'Please add an address']
},
createdAt: {
type: Date,
default: Date.now
}
module.exports = mongoose.model('Bootcamp', BootcampSchema);
為了能對Bootcamp的資料進行操作,我們要在'controllers/bootcamps'寫入與Bootcamp model互動的邏輯
Create:
const bootcamp = await Bootcamp.create(req.body);
Read Specific Bootcamp:
const bootcamp = await Bootcamp.findById(req.params.id);
Read All Bootcamps:
const bootcamps = await Bootcamp.find();
Update Bootcamp:
const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true
});
Delete Bootcamp:
const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id);